package com.jbwz.web.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.jbwz.web.common.session.SecurityUserHolder;
import com.jbwz.web.common.session.SessionUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Objects;

@Configuration
public class MybatisPlusConfig {

  @Bean
  public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    return interceptor;
  }

  @Bean
  public MyMetaObjectHandler metaObjectHandler() {
    return new MyMetaObjectHandler();
  }
}

@Slf4j
class MyMetaObjectHandler implements MetaObjectHandler {

  @Override
  public void insertFill(MetaObject metaObject) {
    setCompanyId(metaObject);
    if (StringUtils.hasLength(metaObject.findProperty("createTime", true))) {
      this.strictInsertFill(
          metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.3(推荐)
      this.strictUpdateFill(
          metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.3(推荐)
    }
  }

  @Override
  public void updateFill(MetaObject metaObject) {
    setCompanyId(metaObject);
    if (StringUtils.hasLength(metaObject.findProperty("updateTime", true))) {
      this.strictUpdateFill(
          metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.3(推荐)
    }
  }

  /**
   * 无效，必须得在实体类的属性上添加注解
   * @param metaObject
   */
  private void setCompanyId(MetaObject metaObject) {
    if (StringUtils.hasLength(metaObject.findProperty("companyId", true))) {
      SessionUser currentUser = SecurityUserHolder.getCurrentUser();
      if (Objects.nonNull(currentUser) && Objects.nonNull(currentUser.getCompanyId())) {
        this.strictFillStrategy(metaObject, "companyId", currentUser::getCompanyId);
      }
    }
  }
}
